﻿using Microsoft.Practices.Unity;
using Sasa.QualityTools.CodeAnalysis.Common;
using Sasa.QualityTools.CodeAnalysis.Core.Models;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sasa.QualityTools.CodeAnalysis.Core.Views;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels.Configurations;
using System.Windows.Forms;
using Sasa.QualityTools.CodeAnalysis.Core.VisualStudio;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Commands.Behaviors.Configuration
{
    public abstract class ConfigureBehaviorBase : ICommandBehavior<CommandExecutionContext>
    {
        private static readonly string BundledRuleSetDirectoryPath = Path.GetFullPath(Path.Combine(Environment.GetEnvironmentVariable("VS100COMNTOOLS"), "..", "..", "Team Tools", "Static Analysis Tools", "Rule Sets"));


        protected abstract string ConfigurationPath { get; }

        protected IUnityContainer Container { get; private set; }


        protected ConfigureBehaviorBase(IUnityContainer container)
        {
            Container = container;
        }


        public abstract void Behave(CommandExecutionContext context);


        protected string BrowseRuleSet()
        {
            var dialog = new OpenFileDialog { Title = "Select RuleSet", DefaultExt = "ruleset", Filter = "RuleSet (*.ruleset)|*.ruleset" };
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            var path = Path.Combine(Path.GetDirectoryName(ConfigurationPath), Path.GetFileName(dialog.FileName));
            if (dialog.FileName == path)
            {
                return path;
            }

            Logger.Info("Copying '{0}' to '{1}'.", dialog.FileName, path);
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            File.Copy(dialog.FileName, path, true);
            
            return path;
        }

        protected void FillRuleSets(CodeAnalysisConfigurationViewModel model)
        {
            var ruleSets = model.GenericConfiguration.RuleSets;
            ruleSets.Add(new RuleSetViewModel { Name = "<None>" });
            RuleSet.Load(BundledRuleSetDirectoryPath).ForEach(o => ruleSets.Add(new RuleSetViewModel(o)));
            RuleSet.Load(Path.GetDirectoryName(ConfigurationPath)).ForEach(o => ruleSets.Add(new RuleSetViewModel(o)));
        }
    }
}
